// packageE/stores/stores.js
var location = require("../../../mybehaviors/location/location");
var app = getApp();
Component({
  behaviors: [location],
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
    bottomShowBol: {
      type: null
    },
    bottomShowBolIndex: {
      type: null
    },
    index: {
      type: null,
    },
    btnFlag: {
      type: null
    },
  },
  // 私有数据，可用于模板渲染
  data: {
    emptyImage:  `${app.globalData.imgPath}image.png`,
    clientWidth: "375",
    active: "3",

    titleName: [
      {
        id: "popularity_short",
        text: "人气商家",
        url: "plugin.store-cashier.frontend.store.store.get-store-list-rank"
      },
      {
        id: "new_short",
        text: "新入驻商家",
        url: "plugin.store-cashier.frontend.store.store.get-store-list-rank"
      },
      {
        id: "preferential_short",
        text: "优惠商家",
        url: "plugin.store-cashier.frontend.store.store.get-store-list-rank"
      },
      {
        id: "nearby",
        text: "附近商家",
        url: "plugin.store-cashier.frontend.store.store.get-store-list-rank"
      }
    ],
    api: "",
    dataJson: {},
    //人气商家数组和分页数据
    shopList0: [],
    isLoadMore0: false,
    page0: 1,
    total_page0: 0,
    //新入驻商家数组和分页数据
    shopList1: [],
    isLoadMore1: false,
    page1: 1,
    total_page1: 0,
    //优惠商家数组和分页数据
    shopList2: [],
    isLoadMore2: false,
    page2: 1,
    total_page2: 0,
    //附近商家数组和分页数据
    shopList3: [],
    isLoadMore3: false,
    page3: 1,
    total_page3: 0,
    is_sales_display: 0, //企业 is_sales_display  0 不显示销量  1显示销量
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      let language = wx.getStorageSync("langIndex");
      this.setData({language: language.en});
    },
    moved() {
    },
    detached() {
    },
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {
  },
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    if (this.data.datas.discount_list.indexOf("1") > -1) {
      this.setData({
        showMun: true,
      });
    } else if (this.data.datas.discount_list.indexOf("1") < 0) {
      this.setData({
        showMun: false,
      });
    }
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
    this._getLocation(()=> {
      if (this.data.datas.tab_list.indexOf("4") > -1) {
        this.chooseTab(" ", "nearby");
        this.setData({active:'3'});
      } else if (this.data.datas.tab_list.indexOf("1") > -1) {
        this.chooseTab(" ", "popularity_short");
        this.setData({active:'0'});
      } else if (this.data.datas.tab_list.indexOf("2") > -1) {
        this.chooseTab(" ", "new_short");
        this.setData({active:'1'});
      } else if (this.data.datas.tab_list.indexOf("3") > -1) {
        this.chooseTab(" ", "preferential_short");
        this.setData({active:'2'});
      }
    });
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {
    },
    hide() {
    },
    resize() {
    },
  },
  methods: {
    // 跳转到店铺
    toRouter(e) {
      let item = e.currentTarget.dataset.item;
      if (item.specify_show == 1) {
        wx.navigateTo({
          url:
					"/packageC/o2o/o2oStore/o2oStore?store_id=" +
					item.id +
					"&fromHome=1",
        });
      } else {
        if (item.store_decorate == 1) {
          wx.navigateTo({
            url: "/packageG/o2o/HomeSeller/HomeSeller?store_id=" + item.id,
          });
        } else {
          wx.navigateTo({
            url: "/packageC/o2o/HomeSeller/HomeSeller?store_id=" + item.id,
          });
        }

      }
    },
    // 打开地图
    goToAdress(e) {
      let latitude = e.currentTarget.dataset.items.latitude;
      let longitude = e.currentTarget.dataset.items.longitude;
      let store_name = e.currentTarget.dataset.items.store_name;
      let point = app.BMapTransqqMap(
        parseFloat(longitude),
        parseFloat(latitude)
      );
      wx.openLocation({
        latitude: point.lat,
        longitude: point.lng,
        scale: 18,
        name: store_name,
      });
    },
    onClick(e) {
      if (e.detail.title == "人气商家") {
        this.setData({
          active: 0,
        });
        this.chooseTab("", "popularity_short");
      } else if (e.detail.title == "新入驻商家") {
        this.setData({
          active: 1,
        });
        this.chooseTab("", "new_short");
      } else if (e.detail.title == "优惠商家") {
        this.setData({
          active: 2,
        });
        this.chooseTab("", "preferential_short");
      } else if (e.detail.title == "附近商家") {
        this.setData({
          active: 3,
        });
        this.chooseTab("", "nearby");
      }
    },
    chooseTab(key, index) {
      // 找到对应的索引
      function pFn(p) {
        return p.id == index;
      }

      this.setData({
        tab: this.data.titleName.findIndex(pFn),
      });
      // console.log(this.data.tab, this.data.titleName, "this.data.titleName");
      this.setData({
        api: this.data.titleName[this.data.tab].url,
      });
      let sorting = this.data.titleName[this.data.tab].id;
      if( sorting == 'preferential_short' ) {
        this.data.datas.discount_type == '1' ? sorting = 'preferential_short_percentage' : sorting = 'preferential_short';
      }
      this.setData({
        [`isLoadMore${this.data.tab}`]: false,
        [`total_page${this.data.tab}`]: 0,
        [`page${this.data.tab}`]: 1,
      });
      let point = app.qqMapTransBMap(
        parseFloat(this.data.point.lng),
        parseFloat(this.data.point.lat)
      );
      this.setData({
        dataJson: {
          lng: point.lng ? point.lng : "",
          lat: point.lat ? point.lat : "",
          city_name: this.data.city,
          page: this.data[`page${this.data.tab}`],
          sorting: sorting,
          is_aggregation: 1
        },
      });
      let category_ids = [];
      if(this.data.datas.list&&this.data.datas.list.length>0){
        this.data.datas.list.forEach(element => {
          category_ids.push(element.id);
        });
        this.data.dataJson.category_ids = category_ids;
      }
      this.getList();
    },
    getList() {
      let that = this;
      // console.log(this.data.api,"api")
      let urlStr = app.getNetAddresss(that.data.api);
      app._postNetWork({
        url: urlStr,
        data: this.data.dataJson,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            that.setData({
              [`shopList${that.data.tab}`]: res.data.data,
              [`total_page${that.data.tab}`]: res.data.last_page,
              is_sales_display: res.data.is_sales_display
            });
            if (that.data[`total_page${that.data.tab}`] <= 1) {
              that.setData({
                [`isLoadMore${that.data.tab}`]: false,
              });
            } else {
              that.setData({
                [`isLoadMore${that.data.tab}`]: true,
              });
            }

            if (
              that.data[`shopList${that.data.tab}`].length >
								that.data.datas.get_number
            ) {
              that.data[`shopList${that.data.tab}`].splice(
                that.data.datas.get_number,
                that.data[`shopList${that.data.tab}`].length -
									that.data.datas.get_number
              );
              that.setData({
                [`shopList${that.data.tab}`]: res.data.data,
                [`isLoadMore${that.data.tab}`]: false,
              });
            }
            // console.log(this.data[`shopList${that.data.tab}`], "aa");
          } else {
            console.log(res.msg);
          }
          // console.log(that.data.shopList0)
        },
        fail: function (res) {
          console.log(res);
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: "none",
          });
        },
      });
    },
    getMoreList() {
      let that = this;
      let point;
      //获取更多数据
      this.setData({
        [`isLoadMore${this.data.tab}`]: false,
      });
      if (
        this.data[`page${this.data.tab}`] >=
					this.data[`total_page${this.data.tab}`]
      ) {
        return;
      } else {
        this.data[`page${this.data.tab}`] =
						this.data[`page${this.data.tab}`] + 1;
        point = app.qqMapTransBMap(
          parseFloat(this.data.point.lng),
          parseFloat(this.data.point.lat)
        );
        let sorting = this.data.titleName[this.data.tab].id;
        if( sorting == 'preferential_short' ) {
          this.data.datas.discount_type == '1' ? sorting = 'preferential_short_percentage' : sorting = 'preferential_short';
        }
        this.setData({
          dataJson: {
            lng: point.lng ? point.lng : "",
            lat: point.lat ? point.lat : "",
            city_name: this.data.city,
            page: this.data[`page${this.data.tab}`],
            sorting: sorting,
            is_aggregation: 1
          },
        });
        let category_ids = [];
        if(this.data.datas.list&&this.data.datas.list.length>0){
          this.data.datas.list.forEach(element => {
            category_ids.push(element.id);
          });
          this.data.dataJson.category_ids = category_ids;
        }
        let urlStr = app.getNetAddresss(that.data.api);
        app._postNetWork({
          url: urlStr,
          data: that.data.dataJson,
          success: (resdata) => {
            var res = resdata.data;
            if (res.result == 1) {
              that.setData({
                is_sales_display: res.data.is_sales_display
              })
              that.setData({
                [`shopList${that.data.tab}`]: that.data[`shopList${that.data.tab}`].concat(res.data.data),
                [`total_page${that.data.tab}`]: res.data.last_page,
              });
              if (
                that.data[`page${that.data.tab}`] >=
									that.data[`total_page${that.data.tab}`]
              ) {
                that.setData({
                  [`isLoadMore${that.data.tab}`]: false,
                });
              } else {
                that.setData({
                  [`isLoadMore${that.data.tab}`]: true,
                });
              }

              if (
                that.data[`shopList${that.data.tab}`].length >
									that.data.datas.get_number
              ) {
                that.data[`shopList${that.data.tab}`].splice(
                  that.data.datas.get_number,
                  that.data[`shopList${that.data.tab}`].length -
										that.data.datas.get_number
                );
                that.setData({
                  [`shopList${that.data.tab}`]: that.data[`shopList${that.data.tab}`],
                  [`isLoadMore${that.data.tab}`]: false,
                });
              }
              // console.log(that.data.shopList0)
            } else {
              that.setData({
                [`page${that.data.tab}`]: [`page${that.data.tab}`] - 1,
                [`isLoadMore${that.data.tab}`]: false,
              });
            }
          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
  },
  observers: {
    'bottomShowBol': function (flag) {
      if (flag && this.data.bottomShowBolIndex == this.data.index && this.data[`isLoadMore${this.data.tab}`]) {
        this.getMoreList();
      }
    },
  }
});
